local addonName, ZLAUTO = ...
local ZL = ZLAUTO.mainFrame
local playerName = ZL.playerName
local pruneCrossRealm = ZL.pruneCrossRealm
local Prefix = ZL.Prefix
local emptytable = ZL.emptytable
local PlayerIsML = ZL.PlayerIsML
local GetStartAndIncrementBid = ZL.GetStartAndIncrementBid
local GetAuctioningCount = ZL.GetAuctioningCount
local isAllSameDigits = ZL.isAllSameDigits
local tableSort = ZL.tableSort
local LootSlotIsItem = ZL.LootSlotIsItem
local isFilterItem = ZL.isFilterItem
local TransmitAddonInfo_Pro = ZL.TransmitAddonInfo_Pro
local padZeros = ZL.padZeros
local msg_gsub = ZL.msg_gsub
local GetCurrentRoster = ZL.GetCurrentRoster
local IsNeedMail = ZL.IsNeedMail
local previousRoster = {} --初始化团队成员


local defaults = {
	profile = {
		point = {
			point = "CENTER",
			relative = "CENTER",
			x = 0,
			y = 0,
		},
		forceHideShow = true,
		countdownTimerJump = 60,
		AdditionalRaidMembers = false,
		AdditonalRaidMembersAmount = 0,
		auctionTimer = 3600,
		auctionTimerRefresh = 1800,
		manualCountdownTimer = 30,
		startBid = 200,
		increment = 50,
		minQuality = -1,
		awardToML = true,
		buttonReenableDelay = 0.5,
		confirmMailAll = true,
        confirmLootAnnounce = false,
		enhanceTimeRemaining = false,
		remindInvalidBid = false,
        remainingTradeTimeBtnValue = true,
	}
}
function ZL:OnProfileEnable()
	-- print("配置变化")
    self.opt = self.db.profile
    TransmitAddonInfo_Pro()
end
local function mainInit(self, event, ...)
    local arg = emptytable(...)
    local AuctionFrame = ZL.AuctionFrame
    if event == "ADDON_LOADED" and arg[1] == "AutoAuction" then
        self:UnregisterEvent("ADDON_LOADED")
        for i = 1, NUM_CHAT_WINDOWS do
            _G["ChatFrame"..i.."EditBox"]:SetAltArrowKeyMode(true)
        end

        SLASH_ZL_RELOAD1 = "/rl"
        SlashCmdList.ZL_RELOAD = ReloadUI
        SLASH_ZL_TOOLBOX1 ="/ac"
        SlashCmdList.ZL_TOOLBOX = function ()
            -- _G["ZLAuctionFrame"]:Show()
            ZL.maxFrame:Hide()
            ZL.AuctionFrame:Show()
        end

        ZL_CURRENT = ZL_CURRENT or {OpenLootList={}, GroupMembersVersion={}}
        ZL_HISTORY = ZL_HISTORY or {}
        ZL_SETTING = ZL_SETTING or {itemLevelSetting={}, itemIdSetting={}, filterItemId={}}
        
        self.db = LibStub("AceDB-3.0"):New("ZL_Profile", defaults) --创建默认配置数据库
        self.db.RegisterCallback(self, "OnProfileChanged", "OnProfileEnable")
		self.db.RegisterCallback(self, "OnProfileCopied", "OnProfileEnable")
		self.db.RegisterCallback(self, "OnProfileReset", "OnProfileEnable")
        self.opt = self.db.profile

        self.options.args.profiles = LibStub("AceDBOptions-3.0"):GetOptionsTable(self.db)
		self.options.args.profiles.order = -1
		LibStub("AceConfig-3.0"):RegisterOptionsTable("金团自动拍卖助手", self.options)

        --Minimap Icon Creation
		self.LDB = LibStub("LibDataBroker-1.1"):NewDataObject(addonName, {
			type = "data source",
			text = addonName,
			icon = "Interface\\AddOns\\" .. addonName .. "\\Images\\ZL.tga",
			OnClick = function(self, button)
				if button == "LeftButton" then
					LibStub("AceConfigDialog-3.0"):Open("金团自动拍卖助手")
				end
			end,
			OnTooltipShow = function(tooltip)
				tooltip:AddLine("金团自动拍卖助手")
				tooltip:AddLine("自动化拍卖，出价和工资分配", 1, 1, 1, false)
				tooltip:AddLine(" ")
				tooltip:AddLine("左键点击|cffffffff : 打开设置|r ")
			end
		})
        self.minimapicon = LibStub("LibDBIcon-1.0")
		self.minimapicon:Register("ZLAUTOLDB", self.LDB, self.db.global)
        
        ZL:CreateAuctionFrame()
        ZL:CreateMaxAuctionFrame()
        ZL:CreateItemSettingFrame()
        ZL:CreateAuctionRecordFrame()
        ZL:CreateRemainingTradeTimeFrame()

        DEFAULT_CHAT_FRAME:AddMessage(Prefix("欢迎回来  >>>".. playerName.."<<<"))
    end
    if event == "PLAYER_LOGIN" then
        --从数据库中加载存在的拍卖物品
        do
            if ZL_CURRENT.auctionlist and (#ZL_CURRENT.auctionlist > 0) then
                for num, _ in ipairs(ZL_CURRENT.auctionlist) do
                    local f = AuctionFrame.entries[num]
                    f:SetValues(num)
                end
            end
        end
        ZL:FrameUpdate()
        _G["ZLAuctionFrameTab1"]:Click()
        if IsInRaid() then
            ZL:Show()
        else
            ZL:Hide()
        end
    end
    if event == "GROUP_ROSTER_UPDATE" then
        -- 函数：获取当前团队成员列表
        local function GetCurrentRoster()
            local roster = {}
            for i = 1, GetNumGroupMembers() do
                local name = GetRaidRosterInfo(i)
                if name then
                    table.insert(roster, name)
                end
            end
            return roster
        end
        -- 函数：检测是否有新成员加入
        local function CheckForNewMembers()
            local currentRoster = GetCurrentRoster()
            if next(previousRoster, nil) then
                for _, name in ipairs(currentRoster) do
                    if (not previousRoster[name]) then
                        -- 新成员加入，发送密语
                        if UnitIsGroupLeader("player") and (name ~= UnitName("player")) and ZL.opt.welcomeMessageEnable and
                            ZL.opt.MessageString and (string.len(ZL.opt.MessageString) > 0) then
                            SendChatMessage(ZL.opt.MessageString, "WHISPER", nil, name)
                            TransmitAddonInfo_Pro() --同步拍卖插件全局参数
                        end
                    end
                end
            end
            -- 更新之前的团队成员列表
            previousRoster = {}
            for _, name in ipairs(currentRoster) do
                previousRoster[name] = true
            end
        end
        if IsInRaid() then
            if not ZL:IsShown() then
                ZL:Show()
                ZL:FrameUpdate()
            end
            CheckForNewMembers()
        else
            -- print("不在团队")
            previousRoster = {}
            ZL.MLname = nil
            ZL:Hide()
        end
    end
    --更换ML人员需要用到这个事件
    if event == "PARTY_LOOT_METHOD_CHANGED" then
        local lootmethod, masterlooterPartyID, masterlooterRaidID = GetLootMethod()
        if lootmethod == "master" and masterlooterRaidID then
            ZL.MLname = UnitName("raid" .. masterlooterRaidID)
        end

        if (ZL_CURRENT.auctionlist) and (#ZL_CURRENT.auctionlist > 0) then
            for num, _ in ipairs(ZL_CURRENT.auctionlist) do
                local f = AuctionFrame.entries[num]
                f:UpdateItemAuctionFrame()
            end
        end
        AuctionFrame:Update()
    end
    --如果是ML打开掉落则开始创建待拍卖窗口
    if event == "LOOT_OPENED" and PlayerIsML() and (not UnitIsPlayer("target")) and IsInInstance() and (select(2, IsInInstance()) == "raid") then
        if (not ZL_CURRENT.OpenLootList) then ZL_CURRENT.OpenLootList = {} end
        if ZL_CURRENT.OpenLootList[UnitGUID("target")] then return end
        ZL_CURRENT.OpenLootList[UnitGUID("target")] = true
        local msgStr = ""
        if GetNumLootItems() <= 0 then return end
        local minQuality = (self.opt.minQuality == -1 and GetLootThreshold() or self.opt.minQuality) --GetLootThreshold()获取当前团队的战利品分配阈值
        local lootList = {}
        for numLoot = 1, GetNumLootItems() do
            if LootSlotIsItem(numLoot) then
                local _, _, lootQuantity, _, lootQuality, _, isQuestItem = GetLootSlotInfo(numLoot)
                local itemlink = GetLootSlotLink(numLoot)
                local itemId = tonumber(itemlink:match("|Hitem:(%d+):"))
                if lootQuality >= minQuality then
                    table.insert(lootList, itemlink)
                end
                if lootQuality >= minQuality and (not isFilterItem(itemId)) then
                    if (not isQuestItem) then --不是任务用品
                        local index = nil
                        if ZL_CURRENT.auctionlist and (#ZL_CURRENT.auctionlist > 0) then
                            for num, data in ipairs(ZL_CURRENT.auctionlist) do
                                if (data.itemId == itemId) and (data.state ~= "success") then
                                    index = num
                                    break
                                end
                            end
                        end
                        if index then
                            local fdata = ZL_CURRENT.auctionlist[index]
                            if ZL_CURRENT.auctionlist[index].state == "auctioning" then --如果是正在拍卖中的物品，则发送消息全员更新，否则不发送消息，只更新RL的数量
                                local tarbidamount = 0
                                tableSort(fdata.bidderlist)
                                if fdata.bidderlist[fdata.itemCount] then
                                    tarbidamount = fdata.bidderlist[fdata.itemCount].bidamount + fdata.bidIncrement
                                else
                                    tarbidamount = fdata.startbidamount
                                end
                                local hasbidamount = ""
                                for i = 1, math.min(fdata.itemCount, #fdata.bidderlist) do
                                    hasbidamount = hasbidamount .. fdata.bidderlist[i].bidamount .. "g，"
                                end
                                msgStr = ("注意：%s，拍卖数量更新为：%d，有效出价：%s下次最低出价：%d，剩余时间：%d秒"):format(
                                    fdata.itemlink, fdata.itemCount + lootQuantity, hasbidamount, tarbidamount, fdata.countdownremaining
                                )
                                SendChatMessage(msgStr, "RAID")
                            end
                            local data = {
                                type = "数量更新",
                                itemId = fdata.itemId,
                                itemindex = fdata.itemindex,
                                itemCount = fdata.itemCount + lootQuantity,
                                countdownremaining = fdata.countdownremaining,
                            }
                            MyAddon:TransmitAddonInfo("AUTOAUC SYNC", data)
                        else
                            --不存在则创建
                            local itemindex = 1
                            if ZL_CURRENT.auctionlist then
                                for _, data in ipairs(ZL_CURRENT.auctionlist) do
                                    if (data.itemId == itemId) then
                                        itemindex = itemindex + 1
                                    end
                                end
                            end
                            local startbidamount, bidIncrement = GetStartAndIncrementBid(itemId)
                            local data = {
                                type = "创建拍卖",
                                itemId = itemId,
                                itemlink = itemlink,
                                itemindex = itemindex,
                                startbidamount = startbidamount,
                                bidIncrement = bidIncrement,
                                state = "waiting",
                                lgnore = false,
                                countdownremaining = 0,
                                isPaused = false,
                                bidderlist = {},
                                itemCount = 1,
                            }
                            MyAddon:TransmitAddonInfo("AUTOAUC SYNC", data)
                        end
                    end
                    if self.opt.awardToML then                                 --掉落物品自动分配给ML
                        local candidateIndex = 1
                        local candidateName = GetMasterLootCandidate(numLoot, candidateIndex) --用于获取在团队副本中分配战利品时的候选者信息
                        while candidateName do
                            if candidateName == playerName then                --当候选人是玩家本人时
                                GiveMasterLoot(numLoot, candidateIndex)
                                break
                            end
                            candidateIndex = candidateIndex + 1
                            candidateName = GetMasterLootCandidate(numLoot, candidateIndex)
                        end
                    end
                end
            end
        end
        if ZL.opt.confirmLootAnnounce and #lootList > 0 then  --拾取通报
            local index = 1
            local function sendMessage()
                if index <= #lootList then
                    print(lootList[index])
                    SendChatMessage(index .. "、" .. lootList[index], "RAID")
                    index = index + 1
                    C_Timer.After(0.3, sendMessage)
                end
            end
            SendChatMessage("拾取通报：", "RAID")
            C_Timer.After(0.3, sendMessage)
        end
    end

    if (event == "CHAT_MSG_RAID") or (event == "CHAT_MSG_RAID_LEADER") or (event == "CHAT_MSG_RAID_WARNING") then
        local msg, sender = arg[1], pruneCrossRealm(arg[2])
        --[=[监控ML信息部分
        if PlayerIsML(sender) then
            --开始拍卖
            do
                local itemindex, itemlink, itemCount, startbidamount, bidIncrement, auctionTimer = string.match(msg,
                    "开始拍卖%[(%d+)%](|c........|Hitem:.+|r)×(%d+)，请在团队聊天中出价，起步价：(%d+)g，每次最低加价：(%d+)g，剩余时间：(%d+)秒")
                if itemindex and itemlink and itemCount and startbidamount and bidIncrement and auctionTimer then
                    itemindex = tonumber(itemindex)
                    itemCount = tonumber(itemCount)
                    startbidamount = tonumber(startbidamount)
                    bidIncrement = tonumber(bidIncrement)
                    auctionTimer = tonumber(auctionTimer)
                    local itemId = tonumber(string.match(itemlink, "|c........|Hitem:(%d+):"))
                    local data, index = FetchDataFromItemId(itemId, itemindex)
                    if (not data) then
                        data = {
                            ["itemId"] = itemId,
                            ["itemlink"] = itemlink,
                            ["itemindex"] = itemindex,
                            ["startbidamount"] = startbidamount,
                            ["bidIncrement"] = bidIncrement,
                            ["state"] = "auctioning",
                            ["lgnore"] = false,
                            ["countdownremaining"] = auctionTimer,
                            ["isPaused"] = false,
                            ["bidderlist"] = {},
                            ["itemCount"] = itemCount,
                        }
                        if (not ZL_CURRENT.auctionlist) then --如果当前不存在拍卖记录，则创建
                            local name, _, difficultyID, _, _, _, _, instanceID = GetInstanceInfo()
                            ZL_CURRENT.auctionlist = {}
                            ZL_CURRENT.name = name
                            ZL_CURRENT.difficultyID = difficultyID
                            ZL_CURRENT.instanceID = instanceID
                            ZL_CURRENT.auctiondate =  date("%Y-%m-%d %H:%M:%S", time())
                            ZL_CURRENT.totalincome = 0
                            ZL_CURRENT.IncomeList = {}
                        end
                        table.insert(ZL_CURRENT.auctionlist, data)
                        index = #ZL_CURRENT.auctionlist
                    else
                        ZL_CURRENT.auctionlist[index].startbidamount = startbidamount
                        ZL_CURRENT.auctionlist[index].bidIncrement = bidIncrement
                        ZL_CURRENT.auctionlist[index].state = "auctioning"
                        ZL_CURRENT.auctionlist[index].countdownremaining = auctionTimer
                        ZL_CURRENT.auctionlist[index].isPaused = false
                        ZL_CURRENT.auctionlist[index].bidderlist = {}
                        ZL_CURRENT.auctionlist[index].itemCount = itemCount
                    end
                    local f = AuctionFrame.entries[index]
                    f:SetValues(index)
                    AuctionFrame:Update()
                end
            end
            --拍卖中的物品新增数量提醒
            do
                --"注意：[%d]%s，当前拍卖数量更新：%d，有效出价：%dg，下次最低出价：%dg，剩余时间：%d秒"
                local itemindex, itemlink, itemCount, auctionTimer = string.match(
                    msg, "注意：%[(%d+)%](|c........|Hitem:.+|r)，当前拍卖数量更新：(%d+)，有效出价：%d+g，下次最低出价：%d+g，剩余时间：(%d+)秒"
                )
                if itemindex and itemlink and itemCount and auctionTimer then
                    itemindex = tonumber(itemindex)
                    itemCount = tonumber(itemCount)
                    auctionTimer = tonumber(auctionTimer)
                    local itemId = tonumber(string.match(itemlink, "|c........|Hitem:(%d+):"))
                    local data, index = FetchDataFromItemId(itemId, itemindex)
                    if data then
                        ZL_CURRENT.auctionlist[index].itemCount = itemCount
                        ZL_CURRENT.auctionlist[index].countdownremaining = auctionTimer
                        local f = AuctionFrame.entries[index]
                        f:SetValues(index)
                    end
                end
            end
            --取消拍卖
            do
                local itemindex, itemlink = string.match(msg, "%[(%d+)%](|c........|Hitem:.+|r)拍卖已取消，本次拍卖无效，等待重新拍卖！")
                if itemindex and itemlink then
                    itemindex = tonumber(itemindex)
                    local itemId = tonumber(string.match(itemlink, "|c........|Hitem:(%d+):"))
                    local data, index = FetchDataFromItemId(itemId, itemindex)
                    if data then
                        local f = AuctionFrame.entries[index]
                        f.Frame1.timer.updateframe:Hide()
                        f.Frame1.statetext:SetText("拍卖已取消，等待重新拍卖")
                        f.Frame1.curbidamounttext:SetText("有效出价：")
                        f.Frame1.curbiddertext:SetText("当前无人出价！")
                        if f.Frame1.timer:IsPaused() then
                            f.Frame1.timer:Resume()
                            f.Frame1.MLframe.PauseBtn:SetText("暂停")
                        end
                        f.Frame1.timer:SetCooldown(0, 0)
                        f.Frame1.bidbox:Disable()
                        f.Frame1.bidBtn:Disable()
                        f.Frame1.autobidBtn:Disable()
                        f.Frame1.autobidBtn:SetText("自动出价")
                        f.maxAutoBid = nil
                        f.Frame1.MLframe.PauseBtn:Disable()
                        f.Frame1.MLframe.CountDownBtn:Disable()
                        f.Frame1.MLframe.reverseBidBtn:Disable()

                        ZL_CURRENT.auctionlist[index].state = "waiting"
                        ZL_CURRENT.auctionlist[index].countdownremaining = 0
                        ZL_CURRENT.auctionlist[index].isPaused = false
                        ZL_CURRENT.auctionlist[index].bidderlist = {}
                        AuctionFrame:Update()
                    end
                end
            end
            --暂停拍卖
            do
                local itemindex, itemlink = string.match(msg, "%[(%d+)%](|c........|Hitem:.+|r)已暂停拍卖！")
                if itemindex and itemlink then
                    itemindex = tonumber(itemindex)
                    local itemId = tonumber(string.match(itemlink, "|c........|Hitem:(%d+):"))
                    local data, index = FetchDataFromItemId(itemId, itemindex)
                    if data then
                        local f = AuctionFrame.entries[index]
                        f.Frame1.timer:Pause()
                        f.Frame1.statetext:SetText("拍卖暂停中...")
                        f.Frame1.bidbox:Disable()
                        f.Frame1.bidBtn:Disable()
                        f.Frame1.autobidBtn:Disable()
                        ZL_CURRENT.auctionlist[index].isPaused = true
                    end
                end
            end
            --继续拍卖
            do
                local itemindex, itemlink = string.match(msg, "%[(%d+)%](|c........|Hitem:.+|r)已恢复拍卖，.+")
                if itemindex and itemlink then
                    itemindex = tonumber(itemindex)
                    local itemId = tonumber(string.match(itemlink, "|c........|Hitem:(%d+):"))
                    local data, index = FetchDataFromItemId(itemId, itemindex)
                    if data then
                        ZL_CURRENT.auctionlist[index].isPaused = false
                        local f = AuctionFrame.entries[index]
                        f.Frame1.timer:Resume()
                        f.Frame1.statetext:SetText("拍卖中。。。")
                        if f.maxAutoBid then
                            f.Frame1.bidbox:Disable()
                            f.Frame1.bidBtn:Disable()
                            f.Frame1.lgnoreBtn:Disable()
                        else
                            f.Frame1.bidbox:Enable()
                            f.Frame1.bidBtn:Enable()
                            f.Frame1.lgnoreBtn:Enable()
                        end
                        f.Frame1.autobidBtn:Enable()
                    end
                end
            end
            --手动倒计时
            do
                local itemindex, itemlink, manualCountdownTimer = string.match(msg, "%[(%d+)%](|c........|Hitem:.+|r)最后(%d+)秒倒计时，请及时出价！")
                if itemindex and itemlink and manualCountdownTimer then
                    itemindex = tonumber(itemindex)
                    manualCountdownTimer = tonumber(manualCountdownTimer)
                    local itemId = tonumber(string.match(itemlink, "|c........|Hitem:(%d+):"))
                    local data, index = FetchDataFromItemId(itemId, itemindex)
                    if data then
                        local f = AuctionFrame.entries[index]
                        f.daoShuStart = GetTime()
                        f.Frame1.timer:SetCooldown(GetTime(), manualCountdownTimer + 1)
                        if f.Frame1.timer:IsPaused() then
                            f.Frame1.timer:Resume()
                            f.Frame1.MLframe.PauseBtn:SetText("暂停")
                            ZL_CURRENT.auctionlist[index].isPaused = false
                        end
                    end
                end
            end
            --拍卖结束:拍卖成功
            do
                --"[%d]%s拍卖成功！获胜者：%s祝贺！" 
                local itemindex, itemlink = string.match(msg, "%[(%d+)%](|c........|Hitem:.+|r)拍卖成功！获胜者：.+祝贺！")
                if itemindex and itemlink then
                    itemindex = tonumber(itemindex)
                    local itemId = tonumber(string.match(itemlink, "|c........|Hitem:(%d+):"))
                    local data, index = FetchDataFromItemId(itemId, itemindex)
                    if data then
                        local f = AuctionFrame.entries[index]
                        f.Frame1.statetext:SetText("拍卖成功！")
                        f.Frame1.bidbox:Disable()
                        f.Frame1.bidBtn:Disable()
                        f.Frame1.autobidBtn:Disable()
                        f.Frame1.autobidBtn:SetText("自动出价")
                        f.maxAutoBid = nil
                        f.Frame1.MLframe.PauseBtn:Disable()
                        f.Frame1.MLframe.PauseBtn:SetText("暂停")
                        f.Frame1.MLframe.CancelBtn:SetText("开始")
                        f.Frame1.MLframe.CountDownBtn:Disable()
                        f.Frame1.MLframe.reverseBidBtn:Disable()

                        ZL_CURRENT.auctionlist[index].state = "success"
                        ZL_CURRENT.auctionlist[index].countdownremaining = 0
                        AuctionFrame:Update()

                        --将获胜者数据添加到数据库
                        local bidderlist = ZL_CURRENT.auctionlist[index].bidderlist
                        tableSort(bidderlist)
                        for i = 1, math.min(ZL_CURRENT.auctionlist[index].itemCount, #bidderlist) do
                            table.insert(ZL_CURRENT["IncomeList"], {
                                player=bidderlist[i].bidder, amount=bidderlist[i].bidamount, notes=itemlink
                            })
                            if (not ZL_CURRENT.playerBalance) then ZL_CURRENT.playerBalance = {} end
                            ZL_CURRENT.playerBalance[bidderlist[i].bidder] =
                                (ZL_CURRENT.playerBalance[bidderlist[i].bidder] or 0) - bidderlist[i].bidamount
                            ZL.AuctionRecordFrame.playerBalanceFrame:Update()
                        end
                    end
                end
            end
            --拍卖结束:流拍
            do
                local itemindex, itemlink = string.match(msg, "%[(%d+)%](|c........|Hitem:.+|r)无人出价，流拍！")
                if itemindex and itemlink then
                    itemindex = tonumber(itemindex)
                    local itemId = tonumber(string.match(itemlink, "|c........|Hitem:(%d+):"))
                    local data, index = FetchDataFromItemId(itemId, itemindex)
                    if data then
                        local f = AuctionFrame.entries[index]
                        f.Frame1.statetext:SetText("流拍！")
                        f.Frame1.curbidamounttext:SetText("有效出价：")
                        f.Frame1.curbiddertext:SetText("当前无人出价！")
                        f.Frame1.bidbox:Disable()
                        f.Frame1.bidBtn:Disable()
                        f.Frame1.autobidBtn:Disable()
                        f.Frame1.autobidBtn:SetText("自动出价")
                        f.maxAutoBid = nil
                        f.Frame1.MLframe.PauseBtn:Disable()
                        f.Frame1.MLframe.PauseBtn:SetText("暂停")
                        f.Frame1.MLframe.CancelBtn:SetText("开始")
                        f.Frame1.MLframe.CountDownBtn:Disable()
                        f.Frame1.MLframe.reverseBidBtn:Disable()
                        ZL_CURRENT.auctionlist[index].state = "failed"
                        ZL_CURRENT.auctionlist[index].countdownremaining = 0
                        AuctionFrame:Update()
                    end
                end
            end
        end
        ]=]
        --监控全员信息出价
        --单个拍卖模式
        do
            if GetAuctioningCount() > 0 then
                local msgStr = ""
                local newBid = nil
                local cmsg = msg_gsub(msg)
                if cmsg:match("^(%d+%.?%d*)[gGkKwW]?$") then
                    newBid = tonumber(cmsg:match("([0-9]+%.?[0-9]*)[wW]"))  --万，检测1W，1.1w
                    if (not newBid) then
                        newBid = tonumber(cmsg:match("([0-9]+%.?[0-9]*)[kK]"))  --千，检测1k,1.1K
                        if (not newBid) then
                            newBid = tonumber(cmsg:match("([0-9]+%.[0-9]*)")) --检测1.1这种数字
                            if (not newBid) then
                                newBid = tonumber(cmsg:match("(%d+)[gG]*")) --检测不带小数点的数字，可能带有g或G
                            end
                        else
                            newBid = math.floor(newBid * 1000)
                        end
                    else
                        newBid = math.floor(newBid * 10000)
                    end
                    if newBid and (newBid <= 1000000) then  --and newBid >= 10 
                        if newBid == 666 then  --newBid == 1 or newBid == 11 or newBid == 99
                            if PlayerIsML() then
                                msgStr = ("\"666\"为高频易混淆词，如需竞价请在后面添加一个0，如：%d0，如不竞价，忽略这条提醒"):format(newBid)
                                SendChatMessage(msgStr, "WHISPER", nil, sender)
                            end
                            return
                        end
                        local oldBid = newBid
                        newBid = string.gsub(tostring(newBid),"%.", "")
                        newBid = tonumber(newBid)
                        local num, index = GetAuctioningCount()
                        if num == 1 then
                            local f = AuctionFrame.entries[index]
                            local fdata = ZL_CURRENT.auctionlist[index]
                            local bidderlist = fdata.bidderlist
                            local tarbidamount = 0
                            tableSort(bidderlist)
                            if bidderlist[fdata.itemCount] then
                                tarbidamount = bidderlist[fdata.itemCount].bidamount + fdata.bidIncrement
                            else
                                tarbidamount = fdata.startbidamount
                            end
                            newBid = padZeros(newBid, tarbidamount)
                            if newBid >= tarbidamount then
                                local isSenderExist = false
                                for bindex, b in ipairs(bidderlist) do
                                    if b.bidder == sender then
                                        ZL_CURRENT.auctionlist[index].bidderlist[bindex].bidamount = newBid
                                        tableSort(ZL_CURRENT.auctionlist[index].bidderlist)
                                        isSenderExist = true
                                        break
                                    end
                                end
                                if (not isSenderExist) then --如不存在，则直接插入
                                    table.insert(ZL_CURRENT.auctionlist[index].bidderlist, {bidder = sender, bidamount = newBid})
                                    tableSort(ZL_CURRENT.auctionlist[index].bidderlist)
                                end
                                ZL_CURRENT.auctionlist[index].countdownremaining = ZL.opt.auctionTimerRefresh--有新的出价，重新更新倒计时
                                f:SetValues(index)
                                if (oldBid == 1 or oldBid == 11 or oldBid == 99) and PlayerIsML() then
                                    msgStr = "插件已记录你的竞拍价:" .. newBid .. "g，如需撤销，请【私聊】我回复：撤销，不要回复错！"
                                    SendChatMessage(msgStr, "WHISPER", nil, sender)
                                end
                            else
                                if PlayerIsML() and ZL.opt.remindInvalidBid then
                                    msgStr = ("%s出价过低，请至少出价%d"):format(fdata.itemlink, tarbidamount)
                                    SendChatMessage(msgStr, "WHISPER", nil, sender)
                                    -- SendChatMessage(msgStr, "RAID")
                                end
                            end
                        else
                            if PlayerIsML() and ZL.opt.remindInvalidBid then
                                msgStr = "当前存在多个物品，请按照如下格式出价：" .. ZL_CURRENT.auctionlist[index].itemlink .. "400/1k/1.1w"
                                SendChatMessage(msgStr, "WHISPER", nil, sender)
                                -- SendChatMessage(msgStr, "RAID")
                            end
                        end
                    -- else
                    --     if PlayerIsML() and ZL.opt.remindInvalidBid then
                    --         msgStr = "出价范围不符合要求（必须大于10g，小于1000000g）"
                    --         SendChatMessage(msgStr, "WHISPER", nil, sender)
                    --         -- SendChatMessage(msgStr, "RAID")
                    --     end
                    end
                end
            end
        end
        --单个或多个拍卖模式
        do
            if GetAuctioningCount() > 0 then
                local msgStr = ""
                local bidItemLink = nil
                local newBid = nil
                local cmsg = msg:gsub("%s", "")
                if cmsg:match("^(|c........|Hitem:.+|r)(%d+%.?%d*)[gGkKwW]?$") then  --cmsg:find("|c........|Hitem:.+|r") == 1
                    bidItemLink, newBid = cmsg:match("(|c........|Hitem:.+|r)%s*([0-9]+%.?[0-9]*)[wW]")
                    if (not bidItemLink) then
                        bidItemLink, newBid = cmsg:match("(|c........|Hitem:.+|r)%s*([0-9]+%.?[0-9]*)[kK]")
                        if (not bidItemLink) then
                            bidItemLink, newBid = cmsg:match("(|c........|Hitem:.+|r)%s*([0-9]+%.[0-9]*)")
                            if (not bidItemLink) then
                                bidItemLink, newBid = cmsg:match("(|c........|Hitem:.+|r)%s*(%d+)[gG]*")
                                newBid = tonumber(newBid)
                            else
                                if PlayerIsML() and ZL.opt.remindInvalidBid then
                                    msgStr = ("【%s】不符合规范，请参照如下格式：%s100/1k/1.1k/1w/1.1w"):format(sender, bidItemLink)
                                    SendChatMessage(msgStr, "WHISPER", nil, sender)
                                    -- SendChatMessage(msgStr, "RAID")
                                end
                                bidItemLink = nil
                                newBid = nil
                            end
                        else
                            newBid = math.floor(tonumber(newBid) * 1000)
                        end
                    else
                        newBid = math.floor(tonumber(newBid) * 10000)
                    end
                    if newBid and bidItemLink then
                        local itemId = tonumber(string.match(bidItemLink, "|c........|Hitem:(%d+):"))
                        local index = nil
                        if ZL_CURRENT.auctionlist then
                            for num, data in ipairs(ZL_CURRENT.auctionlist) do
                                if (data.itemId == itemId) and (data.state == "auctioning") then
                                    index = num
                                    break
                                end
                            end
                        end
                        if index then
                            local f = AuctionFrame.entries[index]
                            local fdata = ZL_CURRENT.auctionlist[index]
                            local bidderlist = fdata.bidderlist
                            local tarbidamount = 0
                            tableSort(bidderlist)
                            if bidderlist[fdata.itemCount] then
                                tarbidamount = bidderlist[fdata.itemCount].bidamount + fdata.bidIncrement
                            else
                                tarbidamount = fdata.startbidamount
                            end
                            if (not f.Frame1.timer:IsPaused()) then
                                if newBid >= tarbidamount then
                                    local isSenderExist = false
                                    for bindex, b in ipairs(bidderlist) do
                                        if b.bidder == sender then
                                            ZL_CURRENT.auctionlist[index].bidderlist[bindex].bidamount = newBid
                                            tableSort(ZL_CURRENT.auctionlist[index].bidderlist)
                                            isSenderExist = true
                                            break
                                        end
                                    end
                                    if (not isSenderExist) then --如不存在，则直接插入
                                        table.insert(ZL_CURRENT.auctionlist[index].bidderlist, {bidder = sender, bidamount = newBid})
                                        tableSort(ZL_CURRENT.auctionlist[index].bidderlist)
                                    end
                                    ZL_CURRENT.auctionlist[index].countdownremaining = ZL.opt.auctionTimerRefresh --有新的出价，重新更新倒计时
                                    f:SetValues(index)
                                else
                                    if PlayerIsML() and ZL.opt.remindInvalidBid then
                                        msgStr = ("%s出价过低，至少出价%d"):format(fdata.itemlink, tarbidamount)
                                        SendChatMessage(msgStr, "WHISPER", nil, sender)
                                        -- SendChatMessage(msgStr, "RAID")
                                    end
                                end
                            else
                                if PlayerIsML() and ZL.opt.remindInvalidBid then
                                    msgStr = ("%s当前暂停拍卖中，请恢复后再出价！"):format(fdata.itemlink)
                                    SendChatMessage(msgStr, "WHISPER", nil, sender)
                                    -- SendChatMessage(msgStr, "RAID")
                                end
                            end
                        else
                            if PlayerIsML() and ZL.opt.remindInvalidBid then
                                msgStr = bidItemLink .. "未拍卖，请选择正在拍卖的物品进行出价！"
                                SendChatMessage(msgStr, "WHISPER", nil, sender)
                                -- SendChatMessage(msgStr, "RAID")
                            end
                        end
                    end
                end
            end
        end
    end
    if (event == "CHAT_MSG_WHISPER") and PlayerIsML() then
        local msg, sender = arg[1], pruneCrossRealm(arg[2])
        if msg == "邮寄" then
            if (not ZL_CURRENT["mailPlayers"]) then ZL_CURRENT["mailPlayers"] = {} end
            if (not IsNeedMail(sender)) then
                table.insert(ZL_CURRENT["mailPlayers"], sender)
            end
            if (not ZL_CURRENT.playerBalance) then ZL_CURRENT.playerBalance = {} end
            if (not ZL_CURRENT.playerBalance[sender]) then
                ZL_CURRENT.playerBalance[sender] = {
                    balance = 0,
                    totalAmount = 0,
                    items = {},
                }
            end
            SendChatMessage("插件已登记！", "WHISPER", nil, sender)
            local senderIndex = nil
            local subgroup = nil
            for i = 1, GetNumGroupMembers() do
                local name, _, _subgroup = GetRaidRosterInfo(i)
                if name == sender then
                    senderIndex = i
                    subgroup = _subgroup
                    break
                end
            end
            if senderIndex and (not InCombatLockdown()) and (UnitIsGroupLeader("player") or UnitIsGroupAssistant("player")) then
                local currentRoster = GetCurrentRoster()
                for i = 8, subgroup+1, -1 do
                    if subgroup == i then
                        break
                    else
                        if #currentRoster[i] < 5 then
                            SetRaidSubgroup(senderIndex, i)
                            break
                        else
                            for j = 1, #currentRoster[i] do
                                local name = currentRoster[i][j]
                                if (not IsNeedMail(name)) then
                                    for k = 1, GetNumGroupMembers() do
                                        local _name = GetRaidRosterInfo(k)
                                        if _name == name then
                                            SwapRaidSubgroup(senderIndex, k)
                                            break
                                        end
                                    end
                                end
                            end
                        end
                    end
                end
            end
        elseif msg == "撤销" then
            local num, index = GetAuctioningCount()
            if num == 1 then
                local itemId = ZL_CURRENT.auctionlist[index].itemId
                local itemindex = ZL_CURRENT.auctionlist[index].itemindex
                MyAddon:TransmitAddonInfo("AUTOAUC REVOKE", {itemId=itemId, itemindex=itemindex, playerName=sender})
            end
            
        end
    end
    local function Trade_UpdateMoney()
        if PlayerIsML() then
            self.tradeMoneyML = GetPlayerTradeMoney() / 10000
            self.tradeMoneyOther = GetTargetTradeMoney() / 10000
        elseif PlayerIsML(GetUnitName("npc", false)) then
            self.tradeMoneyOther = GetPlayerTradeMoney() / 10000
            self.tradeMoneyML = GetTargetTradeMoney() / 10000
        end
    end
    local function Trade_UpdateItemInfo(id)
        local itemLink
        if PlayerIsML() then
            itemLink = GetTradePlayerItemLink(id)
        elseif PlayerIsML(GetUnitName("npc", false)) then
            itemLink = GetTradeTargetItemLink(id)
        end
        if itemLink then
            local itemId = tonumber(string.match(itemLink, "|c........|Hitem:(%d+):"))
            self.MLTradeItems[id] = itemId
        end
    end
    if (event == "TRADE_CLOSED") then
		self.isTrading = false
        ZL.AuctionRecordFrame:Hide()
	end
	if (event == "TRADE_SHOW") then
		self.isTrading = true
        local function PickupContainerItemToTrade(itemId)
            -- 遍历背包中的所有槽位
            for bag = 0, NUM_BAG_SLOTS do
                for slot = 1, C_Container.GetContainerNumSlots(bag) do
                    local GetContainerItemInfo = C_Container.GetContainerItemInfo(bag, slot)
                    if GetContainerItemInfo then
                        local isLocked = GetContainerItemInfo["isLocked"]
                        local _itemId = GetContainerItemInfo["itemID"]
                        local isBound = GetContainerItemInfo["isBound"]
                        if _itemId == itemId and (not isLocked) then  --and (not isBound)
                            -- 找到物品，拾取该物品
                            local isCanTrade = false
                            if isBound then
                                --如果已绑定，检测是否还有剩余交易时间
                                local hyperlink = GetContainerItemInfo["hyperlink"]
                                if (not ZL.ToolTip) then
                                    ZL.ToolTip = CreateFrame("GameTooltip", "TradeTimeRemainingTooltip", nil, "GameTooltipTemplate")
                                end
                                ZL.ToolTip:SetOwner(UIParent, "ANCHOR_NONE")
                                ZL.ToolTip:ClearLines()
                                ZL.ToolTip:SetBagItem(bag, slot)
                                for i = 1, ZL.ToolTip:NumLines() do
                                    local text = _G["TradeTimeRemainingTooltipTextLeft"..i]:GetText()
                                    if text then
                                        local timeRemaining = text:match(BIND_TRADE_TIME_REMAINING:gsub("%%s", "(.+)"))
                                        if timeRemaining then
                                            isCanTrade = true
                                            break
                                        end
                                    end
                                end
                            else
                                isCanTrade = true
                            end
                            if isCanTrade then
                                C_Container.PickupContainerItem(bag, slot)
                                for i = 1, 6 do
                                    local name = GetTradePlayerItemInfo(i)
                                    if (not name) then
                                        ClickTradeButton(i)
                                        break
                                    end
                                end
                                return
                            end
                        end
                    end
                end
            end
        end
        if PlayerIsML() then
            self.tradePartner = (GetUnitName("npc", true))
            if ZL_CURRENT.playerBalance and ZL_CURRENT.playerBalance[self.tradePartner] then
                if ZL_CURRENT.playerBalance[self.tradePartner]["balance"] < 0 then
                    SendChatMessage("总共请支付：".. -ZL_CURRENT.playerBalance[self.tradePartner]["balance"] .. "g", "WHISPER", nil, self.tradePartner)
                end
                if ZL_CURRENT.playerBalance[self.tradePartner]["items"] and #ZL_CURRENT.playerBalance[self.tradePartner]["items"] > 0 then
                    for _, data in ipairs(ZL_CURRENT.playerBalance[self.tradePartner]["items"]) do
                        local itemId = tonumber(string.match(data.notes, "|c........|Hitem:(%d+):"))
                        if (not data.isTraded) and itemId then
                            local isExist = false
                            for i = 1, 6 do
                                local chatItemLink = GetTradePlayerItemLink(i)
                                if chatItemLink and (chatItemLink == data.notes) then
                                    isExist = true
                                    break
                                end
                            end
                            if (not isExist) then
                                PickupContainerItemToTrade(itemId)
                            end
                        end
                    end
                end
            end
        elseif PlayerIsML(GetUnitName("npc", false)) then
            self.tradePartner = (GetUnitName("player", true))
        else
            self.tradePartner = nil
        end
        if PlayerIsML() then
            if (not ZL.AuctionRecordFrame:IsShown()) then
                ZL.AuctionRecordFrame:Show()
            else
                ZL.AuctionRecordFrame.playerBalanceFrame:Update()
            end
            _G["AuctionRecordFrameTab3"]:Click()
            ZL.AuctionRecordFrame:ClearAllPoints()
            ZL.AuctionRecordFrame:SetPoint("TOPLEFT", _G["TradeFrame"], "TOPRIGHT")
        end
		self.tradeMoneyML = 0
		self.tradeMoneyOther = 0
        self.MLTradeItems = {}
        
	end
    if (event == "TRADE_ACCEPT_UPDATE") and self.tradePartner then
        for i = 1, 7 do
			Trade_UpdateItemInfo(i)
		end
        Trade_UpdateMoney()
	end
    if (event == "TRADE_PLAYER_ITEM_CHANGED") then -- and self.tradePartner
        Trade_UpdateItemInfo(arg[1])
	end
    if (event == "TRADE_TARGET_ITEM_CHANGED") then
        Trade_UpdateItemInfo(arg[1])
	end
	if (event == "TRADE_MONEY_CHANGED") and self.tradePartner then
        Trade_UpdateMoney()
	end
    if (event == "UI_INFO_MESSAGE") and self.tradePartner then
        if arg[2] == ERR_TRADE_COMPLETE then
            ZL_CURRENT["playerBalance"][self.tradePartner]["balance"] = (ZL_CURRENT["playerBalance"][self.tradePartner]["balance"] or 0) + self.tradeMoneyOther
			ZL.AuctionRecordFrame.playerBalanceFrame:Update()
            for _, _itemId in ipairs(self.MLTradeItems) do
                for index, data in ipairs(ZL_CURRENT["playerBalance"][self.tradePartner]["items"]) do
                    local itemId = tonumber(string.match(data.notes, "|c........|Hitem:(%d+):"))
                    if (not data.isTraded) and itemId and (itemId == _itemId) then
                        ZL_CURRENT["playerBalance"][self.tradePartner]["items"][index]["isTraded"] = true
                        break
                    end
                end
            end
            self.tradePartner = nil
		end
	end
    if (event == "MAIL_INBOX_UPDATE") and PlayerIsML() then
        if (not ZL.AuctionRecordFrame:IsShown()) then
            ZL.AuctionRecordFrame:Show()
        else
            ZL.AuctionRecordFrame.playerBalanceFrame:Update()
        end
        _G["AuctionRecordFrameTab3"]:Click()
        ZL.AuctionRecordFrame:ClearAllPoints()
        ZL.AuctionRecordFrame:SetPoint("TOPLEFT", _G["MailFrame"], "TOPRIGHT")
    end
    if (event == "PLAYER_INTERACTION_MANAGER_FRAME_HIDE") and (arg[1] == Enum.PlayerInteractionType.MailInfo) and PlayerIsML() then
        ZL.AuctionRecordFrame:Hide()
    end
    if (event == "PLAYER_ENTERING_WORLD") then
        local inInstance, instanceType = IsInInstance()
        if inInstance and instanceType == "raid" then
            ZL:RegisterEvent("UPDATE_INSTANCE_INFO") --当RequestRaidInfo()请求可用时触发
            RequestRaidInfo()
        end
    end
    if (event == "UPDATE_INSTANCE_INFO") then
        local instanceName, _, difficultyID, _, _, _, _, instanceID = GetInstanceInfo()
        local newCD = true
        for i = 1, GetNumSavedInstances() do
            local _, _, _, _difficultyID, locked, _, _, _, _, _, _, _, _, _instanceID = GetSavedInstanceInfo(i)
            if locked and (instanceID == _instanceID) and (difficultyID == _difficultyID) then
                newCD = false
                break
            end
        end
        if newCD and ZL_CURRENT.auctionlist and (#ZL_CURRENT.auctionlist > 0) then --and (ZL_CURRENT.instanceID ~= instanceID) and (ZL_CURRENT.difficultyID ~= difficultyID) 
            local msgStr = "您已进入一个全新副本【|cffffd100" .. instanceName .. "|r】，请确认是否重置当前拍卖数据？"
            StaticPopup_Show("ZL_RESETCURRENTINFO", msgStr)
        end
        ZL:UnregisterEvent("UPDATE_INSTANCE_INFO")
    end
    if event == "BAG_UPDATE_DELAYED" then
        ZL.GetRemainingTradeTime()
    end
    arg:Release()
end

--注册事件
ZL:RegisterEvent("ADDON_LOADED")
ZL:RegisterEvent("CHAT_MSG_RAID")
ZL:RegisterEvent("CHAT_MSG_RAID_LEADER")
ZL:RegisterEvent("CHAT_MSG_RAID_WARNING")
ZL:RegisterEvent("CHAT_MSG_WHISPER")
ZL:RegisterEvent("CHAT_MSG_ADDON")
ZL:RegisterEvent("LOOT_OPENED")
ZL:RegisterEvent("LOOT_CLOSED")
ZL:RegisterEvent("GROUP_ROSTER_UPDATE")
ZL:RegisterEvent("PARTY_LOOT_METHOD_CHANGED")
ZL:RegisterEvent("UNIT_NAME_UPDATE")
ZL:RegisterEvent("TRADE_MONEY_CHANGED")
ZL:RegisterEvent("UI_INFO_MESSAGE")
ZL:RegisterEvent("TRADE_CLOSED")
ZL:RegisterEvent("TRADE_SHOW")
ZL:RegisterEvent("TRADE_ACCEPT_UPDATE")
ZL:RegisterEvent("PLAYER_TRADE_MONEY")
ZL:RegisterEvent("PLAYER_REGEN_ENABLED")
ZL:RegisterEvent("PLAYER_REGEN_DISABLED")
ZL:RegisterEvent("MAIL_SHOW")
ZL:RegisterEvent("MAIL_INBOX_UPDATE")
ZL:RegisterEvent("PLAYER_INTERACTION_MANAGER_FRAME_HIDE") --关闭邮箱触发这个事件
ZL:RegisterEvent("PLAYER_LOGIN")
ZL:RegisterEvent("PLAYER_ENTERING_WORLD")  --IsInInstance函数在 PLAYER_ENTERING_WORLD 后立即返回正确的结果
ZL:SetScript("OnEvent", mainInit)
